import gxipy as gx
import cv2
from datetime import datetime
class CameraSN:
    main = 'GBE23020002'
    side_L = 'GBK22080749'
    side_F = 'GBK22080748'
    tiny = 'GD0180040276'
    def __init__(self):
        pass

class Camera:
    """
    相机各种控制
    :open:打开相机
    :set_exp:设定曝光时间（μs）
    """
    def __init__(self, SN):
        self.device_manager = gx.DeviceManager()
        self.SN = SN
        dev_num, dev_info_list = self.device_manager.update_device_list()


    def open(self):
        self.cam = self.device_manager.open_device_by_sn(self.SN)
        self.cam.ExposureTime.set(200000)

    def set_exp(self, exp_time):
        self.cam.ExposureTime.set(exp_time)

    def stream(self, set):
        if set == 'open' or set == 'Open' or set == 'OPEN' or set == 'ON' or set == 'On' or set == 'on':
            self.cam.stream_on()
        if set == 'close' or set == 'Close' or set == 'CLOSE' or set == 'off' or set == 'Off' or set == 'OFF':
            self.cam.stream_off()

    def close(self):
        self.cam.close_device()

    def show_pic(self, Scaling_ratio=0.2):
        """
        :按下q:停止展示
        :按下s:保存图像
        :return: None
        """
        while True:
            raw_image = self.cam.data_stream[0].get_image()
            # 从彩色原始图像获取 RGB 图像
            rgb_image = raw_image.convert("RGB")
            if rgb_image is None:
                return None
            # 从 RGB 图像数据创建 numpy 数组
            numpy_image = rgb_image.get_numpy_array()
            opencv_image = cv2.cvtColor(numpy_image, cv2.COLOR_RGB2BGR)
            opencv_image_small = cv2.resize(opencv_image, dsize=None, fx=Scaling_ratio, fy=Scaling_ratio, interpolation=cv2.INTER_LINEAR)
            cv2.imshow('press "q" to exit, press "s" to save image', opencv_image_small)
            key = cv2.waitKey(1)

            # 根据按键操作执行相应的操作
            if key == ord('q'):  # 按下 'q' 键退出
                cv2.destroyAllWindows()
                return None
            elif key == ord('s'):  # 按下 's' 键保存图像
                now = datetime.now()
                time_str = now.strftime('%Y-%m-%d-%H-%M-%S-%f')
                cv2.imwrite('./' + self.SN + '-' + time_str + '.bmp', opencv_image)

    def get_pic(self):
        """
        :return: opencv形式的图像
        """
        raw_image = self.cam.data_stream[0].get_image()
        # 从彩色原始图像获取 RGB 图像
        rgb_image = raw_image.convert("RGB")
        if rgb_image is None:
            return None
        # 从 RGB 图像数据创建 numpy 数组
        numpy_image = rgb_image.get_numpy_array()
        opencv_image = cv2.cvtColor(numpy_image, cv2.COLOR_RGB2BGR)
        return opencv_image
